<template>
  <div class="medicalPoint">
    <div class="medicalPoint-header">
      <el-row>
        <el-col :span="1">
          <el-button
            type="primary"
            v-btnpermission="'btn-medicalPointadd'"
            @click="addDialogVisible = true"
            >新增</el-button
          >
        </el-col>
        <!-- 导入 -->
        <el-col :span="1">
          <el-upload
            class="upload"
            :multiple="false"
            :show-file-list="false"
            accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
            :http-request="toLead"
          >
            <template #trigger>
              <el-button v-btnpermission="'btn-medicalPointload'" type="primary"
                >导入</el-button
              >
            </template>
          </el-upload>
        </el-col>
      </el-row>
      <el-card class="drug-head-contatiner-title2">
        <el-form :inline="true" :model="formSearch" class="demo-form-inline">
          <el-form-item label="城市" prop="cityCode">
            <el-tree-select
              v-model="formSearch.cityCode"
              :data="cityTreeOption"
              :props="defaultProps"
              :render-after-expand="false"
              node-key="Code"
              check-strictly
              @change="cs11"
              filterable
            />
          </el-form-item>
          <el-form-item label="场馆名称" prop="venuesCode">
            <el-select
              v-model="formSearch.venuesCode"
              placeholder="--请选择--"
              filterable
            >
              <el-option
                v-for="item in venuesOption"
                :key="item.Code"
                :label="item.CHIDescription"
                :value="item.Code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="医疗点名称" prop="name">
            <el-input v-model="formSearch.name" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">搜索</el-button>
            <el-button @click="onReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
    <div class="medicalPoint-list">
      <el-row>
        <el-col>
          <!-- 预案列表 -->
          <el-table :data="planList" border stripe>
            <!-- 索引列 -->
            <el-table-column
              type="index"
              label="#"
              :index="indexMethod"
            ></el-table-column>
            <el-table-column prop="Name" label="名称"></el-table-column>
            <el-table-column
              prop="VenuesName"
              label="所属场馆"
            ></el-table-column>
            <el-table-column prop="CityName" label="所属城市"></el-table-column>
            <el-table-column
              prop="MedicalPointTypeName"
              label="类型"
            ></el-table-column>
            <el-table-column prop="IsValid" label="是否有效">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.IsValid"
                  :active-value="1"
                  :inactive-value="0"
                  disabled
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="270">
              <template #default="scope">
                <el-button
                  size="small"
                  type="primary"
                  v-btnpermission="'btn-medicalPointupdate'"
                  :icon="Edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="small"
                  type="danger"
                  v-btnpermission="'btn-medicalPointdelete'"
                  @click="DeleteDialog(scope.row.Code)"
                  :icon="Delete"
                  >删除</el-button
                >
                <!-- 导入 -->
                <el-upload
                  class="uploadBtn"
                  :multiple="false"
                  :show-file-list="false"
                  :data="paramLoad(scope.row.Code)"
                  :disabled="scope.row.IfLoadDrugs == 1"
                  accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                  :http-request="toLead1"
                >
                  <template #trigger>
                    <el-button
                      :type="scope.row.IfLoadDrugs ? 'danger' : 'primary'"
                      size="small"
                      :icon="Upload"
                      v-btnpermission="'btn-medicalPointloaddrugs'"
                      >{{
                        scope.row.IfLoadDrugs ? '已导入' : '导入'
                      }}</el-button
                    >
                  </template>
                </el-upload>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="8">
          <el-pagination
            background
            layout="total,prev, pager, next"
            v-model:total="formSearch.total"
            v-model:page-size="formSearch.pageSize"
            v-model:current-page="formSearch.page"
            @current-change="handleCurrentChange"
          />
        </el-col>
      </el-row>
      <!-- 添加预案对话框 -->
      <el-dialog
        title="添加医疗点"
        v-model="addDialogVisible"
        @close="addDislogClosed"
        width="40%"
      >
        <el-form
          :model="addDialogForm"
          :rules="medicalPointFormRulesMixin.addFormRules"
          ref="addFormRef"
          label-width="100px"
          inline
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="活动" prop="ActivityCode">
                <el-select
                  v-model="addDialogForm.ActivityCode"
                  placeholder="--请选择--"
                  filterable
                >
                  <el-option
                    v-for="item in activityOption"
                    :key="item.Code"
                    :label="item.Name"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="所属城市" prop="CityCode">
                <el-tree-select
                  v-model="addDialogForm.CityCode"
                  :data="cityTreeOption"
                  :props="defaultProps"
                  :render-after-expand="false"
                  node-key="Code"
                  check-strictly
                  @change="csAdd"
                  filterable
                /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="所属场馆" prop="VenuesCode">
                <el-select
                  v-model="addDialogForm.VenuesCode"
                  placeholder="--请选择--"
                  filterable
                >
                  <el-option
                    v-for="item in venuesOptionAdd"
                    :key="item.Code"
                    :label="item.CHIDescription"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="医疗点名称" prop="Name">
                <el-input v-model="addDialogForm.Name" /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="医疗点类型" prop="Type">
                <el-select
                  v-model="addDialogForm.Type"
                  placeholder="--请选择--"
                  filterable
                >
                  <el-option
                    v-for="item in typeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="经度" prop="Lng">
                <el-input-number
                  :precision="7"
                  size="large"
                  v-model="addDialogForm.Lng"
                ></el-input-number> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="纬度" prop="Lat">
                <el-input-number
                  :precision="7"
                  size="large"
                  v-model="addDialogForm.Lat"
                ></el-input-number> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="缩放级别" prop="ZoomLevel">
                <el-input-number
                  v-model="addDialogForm.ZoomLevel"
                ></el-input-number> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="是否有效" prop="IsValid">
                <el-checkbox
                  v-model="addDialogForm.IsValid"
                  :true-label="1"
                  :false-label="0"
                /> </el-form-item
            ></el-col>
            <el-col :span="10"></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addFormSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog
        title="修改医疗点"
        v-model="editDialogVisible"
        @close="editDislogClosed"
        width="40%"
      >
        <el-form
          :model="editDialogForm"
          ref="editFormRef"
          :rules="medicalPointFormRulesMixin.editFormRules"
          label-width="100px"
          inline
        >
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="活动" prop="ActivityCode">
                <el-select
                  v-model="editDialogForm.ActivityCode"
                  placeholder="--请选择--"
                  filterable
                >
                  <el-option
                    v-for="item in activityOption"
                    :key="item.Code"
                    :label="item.Name"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="所属城市" prop="CityCode">
                <el-tree-select
                  v-model="editDialogForm.CityCode"
                  :data="cityTreeOption"
                  :props="defaultProps"
                  :render-after-expand="false"
                  node-key="Code"
                  check-strictly
                  @change="csUpdate"
                  filterable
                /> </el-form-item
            ></el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="所属场馆" prop="VenuesCode">
                <el-select
                  v-model="editDialogForm.VenuesCode"
                  placeholder="--请选择--"
                  filterable
                >
                  <el-option
                    v-for="item in venuesOptionUpdate"
                    :key="item.Code"
                    :label="item.CHIDescription"
                    :value="item.Code"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="医疗点名称" prop="Name">
                <el-input v-model="editDialogForm.Name" /> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="医疗点类型" prop="Type">
                <el-select
                  v-model="editDialogForm.Type"
                  placeholder="--请选择--"
                  filterable
                >
                  <el-option
                    v-for="item in typeOption"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="经度" prop="Lng">
                <el-input-number
                  v-model="editDialogForm.Lng"
                  :precision="7"
                  size="large"
                ></el-input-number> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="纬度" prop="Lat">
                <el-input-number
                  v-model="editDialogForm.Lat"
                  :precision="7"
                  size="large"
                ></el-input-number> </el-form-item
            ></el-col>
            <el-col :span="10">
              <el-form-item label="缩放级别" prop="ZoomLevel">
                <el-input-number
                  v-model="editDialogForm.ZoomLevel"
                ></el-input-number> </el-form-item
            ></el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="10">
              <el-form-item label="是否有效" prop="IsValid">
                <el-checkbox
                  v-model="editDialogForm.IsValid"
                  :true-label="1"
                  :false-label="0"
                /> </el-form-item
            ></el-col>
            <el-col :span="10"></el-col>
          </el-row>
        </el-form>
        <template v-slot:footer>
          <span class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editFormSubmit">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, onBeforeMount, reactive } from 'vue';
import { Edit, Delete, Upload } from '@element-plus/icons-vue';
import {
  getDicByTableName,
  getCityTree,
  getDicByDictionary,
  getVenuesListByCityCode,
  getActivityVenues,
} from '@/network/dictionary.js';
import { AddAmbulanceListDrugs } from '@/network/ambulance.js';
import {
  getMedicalPointList,
  addMedicalPoint,
  editMedicalPoint,
  delMedicalPoint,
  addMedicalPointList,
} from '@/network/medicalPoint.js';
import { medicalPointFormRulesMixin } from '@/utils/mixin';
import { ElMessage, ElMessageBox } from 'element-plus';
import { importExcel } from '@/utils/excel';
//分页索引
const indexMethod = (index) => {
  return index + (formSearch.page - 1) * formSearch.pageSize + 1;
};
// 搜索条件
let formSearch = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
  venuesCode: '',
  cityCode: null,
  name: '',
});
const activityOption = ref([]);
const cityTreeOption = ref([]);
const defaultProps = {
  children: 'Children',
  label: 'Name',
  value: 'Code',
};
const cs11 = async (val) => {
  await getVenuesListByCityCode({ code: val }).then((res) => {
    venuesOption.value = res;
    formSearch.medicalPoint = null;
  });
};
const csAdd = async (val) => {
  await getVenuesListByCityCode({ code: val }).then((res) => {
    venuesOptionAdd.value = res;
    addDialogForm.value.VenuesCode = null;
  });
};
const csUpdate = async (val) => {
  await getVenuesListByCityCode({ code: val }).then((res) => {
    venuesOptionUpdate.value = res;
    editDialogForm.value.VenuesCode = null;
  });
};
const onSubmit = async () => {
  let data = {
    page: formSearch.page,
    pageSize: formSearch.pageSize,
    venuesCode: formSearch.venuesCode,
    name: formSearch.name,
    cityCode: formSearch.cityCode,
  };
  await getMedicalPointList(data).then((res) => {
    formSearch.total = res.total;
    planList.value = res.data;
  });
};
const onReset = () => {
  formSearch.venuesCode = '';
  formSearch.name = '';
  formSearch.cityCode = null;
  onSubmit();
};
// 添加角色对话框的显示和隐藏
let addDialogVisible = ref(false);
// 编辑对话框的显示和隐藏
let editDialogVisible = ref(false);
const addFormRef = ref(null);
const editFormRef = ref(null);
let addDialogForm = ref({
  ActivityCode: '',
  CityCode: '',
  VenuesCode: '',
  Name: '',
  Type: '',
  Lng: '',
  Lat: '',
  ZoomLevel: null,
  IsValid: 1,
});

let editDialogForm = ref({
  Code: 0,
  ActivityCode: '',
  CityCode: '',
  VenuesCode: '',
  Name: '',
  Type: '',
  Lng: '',
  Lat: '',
  ZoomLevel: null,
  IsValid: 1,
});
let planList = ref([]);
const venuesOption = ref([]); //搜索中的
const venuesOptionAdd = ref([]); //新增中的
const venuesOptionUpdate = ref([]); //修改中的
const result = async () => {
  await getMedicalPointList(formSearch).then((res) => {
    planList.value = res.data;
    formSearch.total = res.total;
  });
};
const typeOption = ref([]);
const initDic = async () => {
  await getActivityVenues().then((res) => {
    venuesOption.value = res;
    venuesOptionAdd.value = res;
    venuesOptionUpdate.value = res;
  });
  await getDicByTableName({ tableName: 'tactivity' }).then((res) => {
    activityOption.value = res;
  });
  //获取城市
  await getCityTree().then((res) => {
    cityTreeOption.value = res;
  });
  //获取医疗点类型
  await getDicByDictionary({
    type: 'MedicalPointType',
  }).then((res) => {
    typeOption.value = res;
  });
};
//导入Excel表格
const toLead = (e) => {
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      addMedicalPointList(res)
        .then(() => {
          ElMessage.success('导入成功');
          initDic();
          result();
        })
        .catch((err) => {
          console.log(err);
          ElMessage.error('导入失败！');
        });
    } else {
      ElMessage.error('请选择文件');
    }
  });
};
//导入表格
// 参数配置
const paramLoad = (v) => {
  let y = {};
  y.id = v;
  return y;
};
const toLead1 = (e) => {
  console.info(e, 'loadmsg');
  importExcel.methods.importExcel(e, (res) => {
    if (res.length > 0) {
      let newLoadOjb = {};
      newLoadOjb.cityInfo = res;
      newLoadOjb.id = e.data.id;
      AddAmbulanceListDrugs(newLoadOjb, 'btn-medicalPointloaddrugs').then(
        () => {
          ElMessage.success('导入成功');
        },
      );
    } else {
      ElMessage.error('请选择文件');
    }
  });
};
onBeforeMount(() => {
  result();
  initDic();
});
const handleCurrentChange = (val) => {
  formSearch.page = val;
  result();
};
// 添加预案
const addFormSubmit = () => {
  const formRef = addFormRef.value;
  formRef.validate(async (valid) => {
    if (valid) {
      await addMedicalPoint(addDialogForm.value)
        .then(() => {
          ElMessage({
            type: 'success',
            message: '增加成功！',
          });
          result();
          addDialogVisible.value = false;
        })
        .catch(() => {
          ElMessage({
            type: 'error',
            message: '增加失败！',
          });
        });
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};
// 修改
const showEditDialog = (row) => {
  editDialogVisible.value = true;
  editDialogForm.value = JSON.parse(JSON.stringify(row));
};
const editFormSubmit = () => {
  const formRef = editFormRef.value;
  formRef.validate(async (valid) => {
    if (valid) {
      await editMedicalPoint(editDialogForm.value).then(() => {
        ElMessage({
          type: 'success',
          message: '修改成功！',
        });
        result();
        editDialogVisible.value = false;
      });
    } else {
      console.log('error submit!!');
      return false;
    }
  });
};
// 删除
const DeleteDialog = (id) => {
  ElMessageBox.confirm('确定删除该预案吗？', '提示', {
    type: 'warning',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
  }).then(async () => {
    await delMedicalPoint({ code: id }).then(() => {
      ElMessage({
        type: 'success',
        message: '删除预案成功！',
      });
      result();
    });
  });
};
const addDislogClosed = () => {
  // addDialogVisible.value = false;
  // addDialogForm.value = {};
  addFormRef.value.resetFields();
  addFormRef.value.clearValidate();
};
const editDislogClosed = () => {
  editFormRef.value.resetFields();
  editFormRef.value.clearValidate();
};
</script>

<style lang="scss" scoped>
.medicalPoint {
  margin: 14px 15px 14px;
  .medicalPoint-header {
    .drug-head-contatiner-title2 {
      font-size: 18px;
      font-weight: bold;
      color: #333;
      margin-top: 14px;
    }
  }
  .medicalPoint-list {
    margin-top: 14px;
  }
}
.uploadBtn {
  margin: 10px;
  display: inline;
}
</style>
